package club.ljwang.controller;

import club.ljwang.constant.MessageConstant;
import club.ljwang.constant.RedisConstant;
import club.ljwang.entity.PageResult;
import club.ljwang.entity.QueryPageBean;
import club.ljwang.entity.Result;
import club.ljwang.pojo.Setmeal;
import club.ljwang.service.SetmealService;
import club.ljwang.utils.QiniuUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;

/**
 * @Auther: wangl
 * @Date: 2020/2/27 21:57
 * @Description:
 */


@RestController
@RequestMapping("setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return setmealService.findPage(queryPageBean);
    }

    @RequestMapping("upload")
    public Result upload(MultipartFile imgFile){
        try {
            String originalFilename = imgFile.getOriginalFilename();
            int index = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(index);
            String newFileName = UUID.randomUUID().toString() + suffix;
            QiniuUtil.upload(imgFile.getBytes(),newFileName);

            //把所有上传成功的图片文件名 保存到Redis中
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,newFileName);//连接需要关闭

            return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }

    }


    @RequestMapping("add")
    public Result add(@RequestBody Setmeal setmeal){

        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        return setmealService.add(setmeal);

    }


}
